<?php
namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;
use App\Cafe;
use App\City;
use App\Message;
use App\Article;
use App\Goods;
use App\Swiper;
use App\Partner;
use App\District;
use App\User_likeCafe;
use App\UserVisitedCafe;
use App\Tags;
use App\Dicts;
use App\Beans;
use App\Party;
use App\Cuppings;
use App\Users;
use App\User_order;
use App\Party_supply;
use App\Cupping_data;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use App\Supplys;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis as Redis;
use QCloud\Cos\Api;
use QCloud\Cos\Auth;
class APIController extends BaseController
{
    // use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /*
     * tag列表接口
     */
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */

//多次有效签名


    public function wechat()
    {
        echo function_exists("imagecreate");
        echo "121";
// var_dump(gd_info());
        phpinfo();
    }
    public function Impl_createNonreusableSignature(Request $request){
        $filepath=$request->filepath;
        Cosapi::setRegion('tj');
        $rs=Auth::createNonreusableSignature('onecafe',$filepath);
        // dd($rs);
        // var_dump($rs);
        echo $rs;

    }


    //单次有效签名
    public function Impl_createReusableSignature(Request $request){

        $bucket = 'onecafe';

        $config = array(
            'app_id' => '1253709024',
            'secret_id' => 'AKIDvkT2ResaddffU7Jr0zmOp6CC2JZl6958',
            'secret_key' => '3vrt1HPLCwp0406Meoo1c7nqxmS6Zs17',
            'region' => 'tj',   // bucket所属地域：华北 'tj' 华东 'sh' 华南 'gz'
            'timeout' => 60
            );

        date_default_timezone_set('PRC');
        $cosApi = new Api($config);

        // 获取签名
        $ret = $cosApi->getReusableSignature($bucket);
        echo $ret;
    }
    public  function Impl_userOrder(Request $request){
        $user_order=User_order::create($request->all());
        return response()->json($user_order);
    }
    public function Impl_tagslist(Request $request){
        $orderBy=$request->input('orderBy') ?: "sort";
        $orderSort=$request->input('orderSort') ?: "asc";
        $dataLength=$request->input('dataLength');

        $partner_id= $request->input('partner_id');
        $category= $request->input('category');
        $assist_1= $request->input('assist_1');
        $home_tag= $request->input('home_tag');
        $barista_id= $request->input('barista_id');
        if($category){
            $tags=Tags::where('category',$category)->where('status','=',1);
        }else{
            $tags=Tags::where('status','=',1);
        }

        if($partner_id){
            $tags=$tags->where('partner_id','=',$partner_id);
        }


        if($assist_1)       //辅助1，首页显示的标签，基本为杯测活动或者其它活动，后续可能为课程
            $tags = $tags->where('assist_1','>',0)->orderBy('assist_1', 'asc');
        if($home_tag)       //辅助1，首页显示的标签，基本为杯测活动或者其它活动，后续可能为课程
            $tags = $tags->where('home_tag','>',0)->orderBy('home_tag', 'asc');
        

        if($orderSort=="asc")
            $tags=$tags->orderBy('sort', 'asc');
        else
            $tags=$tags->orderBy('sort', 'desc');



        $tags=$tags->where('show_in_app',1)->get();
        foreach($tags as $p){
            $p->cafe=$p->showcafe;
            $goods=$p->goods;
            foreach ($goods as $good) {
                # code...
                $good->photos;
            }
        }

        

        // $sorted->values()->all();

        if($dataLength)
            $tags=$tags->take($dataLength);
        else
            $tags=$tags->take(10);

        // $tags = $tags->orderBy('name');

        
        foreach ($tags as $tag) {
            $tag = $this->tagMoreInfo($tag);
        }


        return response()->json($tags);
    }
    public function Impl_dictsList(Request $request){
        $orderBy=$request->input('orderBy') ?: "id";
        $orderSort=$request->input('orderSort') ?: "asc";
        $dataLength=$request->input('dataLength');

        $category= $request->input('category');
        if($category){
            $dicts=Dicts::where('category',$category)->get();
        }
        

        if($orderSort=="asc")
            $dicts=$dicts->sortBy($orderBy);
        else
            $dicts=$dicts->sortByDesc($orderBy);


        if($dataLength)
            $dicts=$dicts->take($dataLength);
        else
            $dicts=$dicts->take(10);


        return response()->json($dicts);
    }

    public function Impl_partyList(Request $request){
        $partys=Party::all();

        $cafe_id=$request->input('cafe_id');
        $category=$request->input('category');
        $status=$request->input('status');
        $orderBy=$request->input('orderBy') ?: "id";
        $orderSort=$request->input('orderSort') ?: "asc";
        $dataLength=$request->input('dataLength');


        if($cafe_id){
            $partys=$partys->where('cafe_id',$cafe_id);
        }
        if($category){
            $partys=$partys->where('category','1');
        }
        if($status){
            $partys=$partys->where('status','1');
        }

        if($orderSort=="asc")
            $partys=$partys->sortBy($orderBy);
        else
            $partys=$partys->sortByDesc($orderBy);
        if($dataLength)
            $partys=$partys->take($dataLength);
        else
            $partys=$partys->take(10);
        $returnArr=array();
        foreach($partys as $party){
            $cafe = $party->cafe;
            if($party->banner==null)
                $party->banner = $cafe->logo;
            array_push($returnArr, $party);
        }   
        return response()->json($returnArr);
    }
    public function partyDetail2(Request $request){
        $id = $request->id;
        $party=Party::find($id);
        $party->photos=$party->photos;
        return response()->json($party);

    }
    public function Impl_partyDetail(Request $request){
        $id=$request->input('party_id');
        $cuppingData=$request->input('cuppingData');
        $party=Party::find($id);
        $theUser = $this->getUserByAppUserSession($request->input('loginSession'));


        $beans=$party->beans;
        foreach ($beans as $bean) {         //得到样本的豆子
            $partyBean = Party_supply::where('party_id', $party->id)->where('supply_id', $bean->id)->first();
            $bean->number = $partyBean->number;

            if($party->cupping==22)        //返回SCAA杯测数据
            {
                $cuppingData = Cupping_data::where('party_id', '=', $party->id)->where('supply_id', '=', $bean->id)->where('user_id', '=', $theUser->id)->get();

                // $bean->cuppingData = $cuppingData;
                $totalScore = 0;
                foreach ($cuppingData as $row) {
                    if($row->tag_id==730)   //干湿香
                    $bean->fragrance=$row->score;
                    if($row->tag_id==731)   //干香，不计入分值
                    $bean->dry=$row->score;
                    if($row->tag_id==732)   //干香，不计入分值
                    $bean->break=$row->score;
                    if($row->tag_id==730)   //干湿香
                    $bean->fragrance=$row->score;
                    if($row->tag_id==733)   //风味
                    $bean->flavour=$row->score;
                    if($row->tag_id==734)   //回味值
                    $bean->afterTaste=$row->score;   
                    if($row->tag_id==735)   //酸度
                    $bean->acidity=$row->score;
                    if($row->tag_id==754)   //酸的亮度，不计入分值
                    $bean->acidityIntensity=$row->score;

                    if($row->tag_id==736)   //醇厚度
                    $bean->mouthFeel=$row->score;
                    if($row->tag_id==755)   //醇厚度等级，不计入分值
                    $bean->mouthFeelLevel=$row->score;

                    if($row->tag_id==737)   //  
                    $bean->uniformity=$row->score;  
                    if($row->tag_id==738)   //
                    $bean->balance=$row->score;
                    if($row->tag_id==739)   //
                    $bean->cleanCup=$row->score;
                    if($row->tag_id==740)   //
                    $bean->sweetness=$row->score;   
                    if($row->tag_id==741)   //
                    $bean->overall=$row->score;

                    if($row->tag_id==756)   // 香气质量
                    $bean->qualities=$row->words;
                    if($row->tag_id==757)   // 香气质量
                    $bean->words=$row->words;

                    if($row->score)
                        $totalScore += $row->score;     
                }
                $bean->totalScore = $totalScore;
            }
            if($party->cupping==23)        //返回COE杯测数据
            {
                $cuppingData = Cupping_data::where('party_id', '=', $party->id)->where('supply_id', '=', $bean->id)->where('user_id', '=', $theUser->id)->get();
                $totalScore = 0;
                foreach ($cuppingData as $row) {
                    if($row->tag_id==780)   //干湿香1
                        $bean->cleanCup=$row->score;
                    if($row->tag_id==781)   //2
                        $bean->sweetNess=$row->score;
                    if($row->tag_id==782)   //3
                        $bean->acidity=$row->score;
                    if($row->tag_id==783)   //4
                        $bean->mouthFeel=$row->score;
                    if($row->tag_id==784)   //5
                        $bean->flavor=$row->score;
                    if($row->tag_id==785)   //6
                        $bean->afterTaste=$row->score;  
                    if($row->tag_id==810)   //7
                        $bean->balance=$row->score;  
                    if($row->tag_id==811)   //8
                        $bean->overall=$row->score;                         
                    if($row->tag_id==812)   //加权
                        $bean->weight=$row->score;  


                    if($row->tag_id==1)   //颜色
                    {
                        $bean->color=$row->words; 
                    }

                    if($row->score)
                        $totalScore += $row->score;     
                }
                $bean->totalScore = $totalScore;
            }
        }

        $samples = $beans->sortBy('number');
        $arr = array();
        foreach ($samples as $sample) {
            $sample = $this->supplyMoreInfo($sample);
            array_push($arr, $sample);
        }

        $party->samples=$arr;
        $party->sales = $party->sales; 
        $users = $party->users; 
        $cafe = $party->cafe; 
        $party->cafeInfo = $this->cafeMoreInfo($cafe);
        if($party->banner==null)
            $party->banner = $cafe->logo;
        if($party->summary==null)
            $party->summary = '';
        

        $party->payed=0;
        foreach ($users as $user) {         //是否已经报名参加
            if($user->id == $theUser->id)
                $party->payed=1;
        }
        return response()->json($party);
    }
    

    public function Impl_cuppingList(Request $request){
        $cuppings=Cuppings::all();
        $returnArr=array();
        foreach($cuppings as $cupping){
            array_push($returnArr, $cupping);
        }   
        return response()->json($returnArr);
    }
    /*
    * supply列表接口
    */
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function Impl_supplyList(Request $request){
        $lat=$request->input('lat');
        $lng=$request->input('lng');



        $dataLength=$request->input('dataLength');
        $category = $request->input('category');
        $barista_id = $request->input('barista_id');
        $assist_tag = $request->input('assist_tag');
        $show_in_app = $request->input('show_in_app');
        $imgNeed = $request->input('imgNeed');      //是否需要图片展示，需要的话去掉没有图片的
        

        $supplys = Supplys::all();
        //如果是有附近信息
        if(!empty($lat))
        {
            $supplys = $this->getNearbySupplys($lat,$lng); 
            
        }
        
        if($category){
            $supplys=$supplys->where('category',(int)$category);
        }
        if($show_in_app){
            $supplys=$supplys->where('show_in_app','1');
        }
        if($barista_id){
            $supplys=$supplys->where('barista_id',$barista_id);
        }
        if($assist_tag){
            $supplys=$supplys->where('assist_tag',(int)$assist_tag);
        }

        
        if($dataLength)
            $supplys=$supplys->take($dataLength);
        else
            $supplys=$supplys->take(10);

        $returnArr=array();
        foreach($supplys as $supply){
            $supply->cafe=$supply->showcafe;
            $supply->flavours=$supply->tags; 
            $sales = $supply->sales; 
            foreach ($sales as $sale) {
                $sale->specification;
            }

            if($supply->continent)
            {
                $supply->continent=$supply->getContinent;
            }
            if($supply->country)
            {
                $supply->country=$supply->getCountry;
            }
            if($supply->method)
            {
                $supply->method=$supply->getMethod;
            }
            if($supply->roast)
            {
                $supply->roast=$supply->getRoast;
            }
            if($supply->assist_tag)
            {
                $supply->assistTag=$supply->getAssistTag;
            }
            $supply->photos = $supply->photos;

            array_push($returnArr, $supply);
        }   
        return response()->json($returnArr);
    }

    public function Impl_goodsList(Request $request)
    {
        $tag_id = $request->input('tag_id');
        $partner_id = $request->input('partner_id');
        $dataLength=$request->input('dataLength');

        $goods = Goods::all();

        if($tag_id>0){
            $goods=$goods->where('tag_id',$tag_id);
        }
        if($partner_id>0){
            $goods=$goods->where('partner_id',$partner_id);
        }

        if($dataLength)
            $goods=$goods->take($dataLength);
        else
            $goods=$goods->take(10);



        foreach ($goods as $good) {
            # code...
            $sales = $good->sales;

            foreach ($sales as $sale) {
                $sale->specification;
            }

        }
        return response()->json($goods);

    }

    //得到最近的50个咖啡馆
    private function get50Cafes($lat,$lng)
    {
        $latlng = $lng.",".$lat;
        $cityCode=$this->getCitycodeByGps($latlng);

        $cafes = Cafe::where('status', 1)->get();
        if($cityCode)
            $cafes=$cafes->where('citycode', $cityCode);  
        

        //初步筛选之后，如果有坐标，计算距离，并按照距离排序
        foreach ($cafes as $cafe) {
            if(!empty($cafe->latlng))
            {
             $arr = explode(',',$cafe->latlng);
             $cafelng = $arr[0];
             $cafelat = $arr[1];
             $distance = $this->distance($lat,$lng,$cafelat,$cafelng);
             $cafe->distance=$distance; 
         }  
     } 
     $orderBy="distance";
     $orderSort="asc";


     $cafes=$cafes->sortBy($orderBy);   
        // $cafes=array_slice($cafes,0,50);
     return $cafes;
 }
 private function getNearbySupplys($lat,$lng)
 {
    $cafes=$this->get50Cafes($lat,$lng);

    $supplys = collect();
    foreach ($cafes as $cafe) {
        $cafeSupplys=$cafe->supplys;
            // $cafeSupplys=$cafeSupplys->where('status',1);
        foreach ($cafeSupplys as $supply) {
            $supply->distance=$cafe->distance;
            $supplys->push($supply);
        } 
    }
    $supplys = $supplys->where('status',1);

        //根据id分组，选取第一个，去掉相同的supplys
    $supplys = $supplys->groupBy('id');
    $returnSupplys = collect();
    foreach ($supplys as $item) {
        $returnSupplys->push($item[0]);
    }
    return $returnSupplys;
}

    public function Impl_articleDetail(Request $request){
        $id=$request->input('article_id');
        $article=Article::find($id);
        $goods = $article->goods; 
        $article->partner; 
        $photos = $article->photos; 

        $arr = array();
        $index=0;
        foreach ($photos as $photo) {
            $index++;
            $photo->sort =$index;
            array_push($arr, $photo);
        }
        $article->photosArr = $arr;

        foreach ($goods as $good) {
            # code...
            $good->photos;
            $good->sales;
        }
        
        return response()->json($article);     
    }
    public function Impl_goodsDetail(Request $request){
        $id=$request->input('goods_id');
        $goods=Goods::find($id);

        $goods->partner;
        $sales = $goods->sales;
        $max = $sales->max("price");
        $min = $sales->min("price");
        if($max>$min)
            $goods->priceScope=$min."-".$max;
        else
            $goods->priceScope=$min;

        foreach ($goods->tags as $tag) {
            $tag->specifications;
        }
        


        $photos = $goods->photos->sortBy('sort');
        $videos = $goods->videos->sortBy('sort');
        // $photos = $photos->sortBy('sort');

        $arr = array();
        $index=0;
        foreach ($photos as $photo) {
            $index++;
            $photo->sort =$index;
            array_push($arr, $photo);
        }
        $goods->photosArr = $arr;


        $arr2 = array();
        $index2=0;
        foreach ($videos as $video) {
            $index2++;
            $video->sort =$index2;
            array_push($arr2, $video);
        }
        $goods->videosArr = $arr2;


        return response()->json($goods);     
    }

    /*
     * 根据tag_id获取标签详情
     */
    public function Impl_detailtag(Request $request){
        $id=$request->input('tag_id');
        $cafeStar=$request->input('star');
        $tag=Tags::find($id);
        $phots=$tag->photos;
        $cafe=$tag->showcafe;
        $cafes=$tag->cafes;
        $tag->tagPhotos=$phots;
        $tag->cafe=$cafe;

        $cafes = $cafes->sortByDesc('id');
        $cafesArr = array();
        foreach ($cafes as $cafe) {
            if($cafe->status)
            {
                $tags=$cafe->tags;
                $cafe->cafeTags=$tags->where('category',3);

                $photos = $cafe->photos()->get();
                $photos = $photos->sortBy('sort');
                if(empty($cafe->cover))
                    $cafe->cover = $photos->first()->url; 

                if($cafe->star>$cafeStar)       //显示星级>x
                array_push($cafesArr, $cafe);
            }   
        }
        $tag->cafesArr = $cafesArr;
        return response()->json($tag);     
    }
    public function Impl_roleUsers(Request $request){
        $id=$request->input('role_id');
        $tag=Tags::find($id);

        $tag->users;
        return response()->json($tag);
    }
    public function Impl_detailDict(Request $request){
        if(!empty($request->input('dict_id')))
        {
            $id=$request->input('dict_id');
            $dict=dicts::find($id);
            
            return response()->json($dict);
        }
        else
            return response()->json("缺少表情id");
    }
    /*
    * 根据supply_id获取标签详情
    */
    public function Impl_detailSupply(Request $request){
        if(!empty($request->input('supply_id')))
        {
            $id=$request->input('supply_id');
            $supply=Supplys::find($id);
            $photos=$supply->photos;
            $sales=$supply->sales;
            $imgUrls=$this->getImgUrls($photos);
            $cafe=$supply->showcafe;
            if(!empty($cafe))
                $cafe = $this->cafeMoreInfo($cafe);
            $cafes=$supply->cafes;
            $supply->supplyPhotos=$photos;
            if(empty($imgUrls))
                array_push($imgUrls, $supply->icon);
            $supply->imgUrls=$imgUrls;

            $supply->flavours=$supply->tags;    

            
            if($supply->continent)
            {
                $supply->continent=$supply->getContinent;
            }
            if($supply->country)
            {
                $supply->country=$supply->getCountry;
            }
            if($supply->method)
            {
                $supply->method=$supply->getMethod;
            }
            if($supply->roast)
            {
                $supply->roast=$supply->getRoast;
            }
            if($supply->assist_tag)
            {
                $assistTag=$supply->getAssistTag;
                $assistTag->photos = $assistTag->photos;
                $supply->assistTag=$assistTag;
            }

            $supply->cafe=$cafe;

            $supply->cafes =$cafes;
            return response()->json($supply);
        }
        else
            return response()->json("");
    }

    private function getImgUrls($photos)
    {
        $imgUrls=array();
        foreach ($photos as $photo) {
            array_push($imgUrls, $photo->url);
        }
        return $imgUrls;
    }

    private function cafeMoreInfo($cafe)
    {
        $supplys=$cafe->supplys;
        foreach ($supplys as $supply) {
            $supply->photos=$supply->photos;   
        }
        
        // $cafe->cafeTags=$tags->where('category',3);
        $cafe->coffeeSupplyPublic=$supplys->where('category',7)->where('public',1);
        $cafe->coffeeSupplyPrivate=$supplys->where('category',7)->where('public',0);
        $cafe->danpinSupply=$supplys->where('category',8);
        $cafe->dessertSupply=$supplys->where('category',9);
        $cafe->magazineSupply=$supplys->where('category',14);

        foreach ($cafe->danpinSupply as $supply) {
            $supply->flavours=$supply->tags; 
        }
        return $cafe;
    }
    private function tagMoreInfo($tag)
    {
        $cafes=$tag->cafes;

        $cafes = $cafes->where('status', 1)->where('star', 5)->sortByDesc('id');
        $cafes = $cafes->take(6);
        $cafesArr = array();
        foreach ($cafes as $cafe) {
            $photos = $cafe->photos()->get();
            $photos = $photos->sortBy('sort');
            if(empty($cafe->cover))
                $cafe->cover = $photos->first()->url; 
            array_push($cafesArr, $cafe); 

        }
        $tag->cafesArr = $cafesArr;
        return $tag;
    }
    private function supplyMoreInfo($supply)
    {

        $supply->continent = $supply->getContinent;
        $supply->country = $supply->getCountry;
        $supply->method = $supply->getMethod;
        
        return $supply;
    }
    /*
     * 根据id获取咖啡店详情
     */
    public function Impl_detailCafe(Request $request){
        $cafe_id=$request->input('cafe_id');
        $lat=$request->input('lat');
        $lng=$request->input('lng');
        $cafe=Cafe::find($cafe_id);
        $tags=$cafe->tags;
        $supplys=$cafe->supplys;
        $cafe->cafeTags=$tags->where('category',3);
        $cafe->coffeeSupplyPublic=$supplys->where('category',7)->where('public',1);
        $cafe->coffeeSupplyPrivate=$supplys->where('category',7)->where('public',0);
        $cafe->danpinSupply=$supplys->where('category',8);
        $cafe->dessertSupply=$supplys->where('category',9);

        foreach ($cafe->danpinSupply as $supply) {
            $supply->flavours=$supply->tags; 
        }

        if($cafe->week)
        {
            $cafe->week=$cafe->getWeek;
        }

        if($cafe->weekend)
        {
            $cafe->weekend=$cafe->getWeekend;
        }          

        $arr = explode(',',$cafe->latlng);
        $cafelng = $arr[0];
        $cafelat = $arr[1];
        $distance = $this->distance($lat,$lng,$cafelat,$cafelng);
        $cafe->distance=$distance;


        $user=$this->getUserByAppUserSession($request->input('loginSession'));

        $cafe->userLikeCafe=$this->getUserLikeCafe($user->id,$cafe->id);
        $cafe->userVisitCafe=$this->getUserVisitCafe($user->id,$cafe->id);

        $cafe->likedUsers=count($cafe->likedUsers);
        $cafe->visitedUsers=count($cafe->visitedUsers);
        $cafe->infoPartners=$cafe->infoPartners;

        $photos = DB::table('photos')
        ->where('cafe_id', '=', $cafe->id)
        ->where('message_id', '=', 0)
        ->orderBy('sort', 'asc')
        ->take(9)->get();

        $photosArr = array();
        foreach ($photos as $photo) {
            array_push($photosArr, $photo->url);
        }

        $cafe->qrcode='https'.substr($cafe->qrcode, 4);


        $cafe->cafePhotos=$photos;
        $cafe->photosArr=$photosArr;
        return response()->json($cafe);
    }

    /**
     * @param 城市编码 citycode  坐标 latlng  区编码 adcode  标签id tag_id  页数(默认值1) page 数量（默认值10）count
     * @return 咖啡馆列表
     */
    public function Impl_cafesNearby(Request $request)
    {
        $lat=$request->input('lat');
        $lng=$request->input('lng');

        //根据坐标拿到城市，先筛选一遍
        $latlng = $lng.",".$lat;
        $cityCode = $this->getCitycodeByGps($latlng);
        //遍历计算距离，返回前20个
        $cafes = Cafe::where('status', 1)->get();
        $cafes=$cafes->where('citycode', $cityCode);    //先筛选城市，缩小处理范围，没测试获得城市编码的成本！！！


        $theCafes = collect();  
        foreach ($cafes as $cafe) {    
            if($cafe->latlng>"")
            {
                $arr = explode(',',$cafe->latlng);
                $cafelng = $arr[0];
                $cafelat = $arr[1];
                $distance = $this->distance($lat,$lng,$cafelat,$cafelng);
                $cafe->distance=$distance;
                if($distance<2)         //保留2公里内的咖啡馆
                {
                    $theCafes->push($cafe);
                }
            }   
        }
        // $cafes = $cafes->take(3);              //最近的多少个
        $theCafes = $theCafes->sortBy("distance");   //距离排序
        $returnCafes = array();         //返回数组

        // 整理数据
        $index=0;
        foreach ($theCafes as $cafe) {
            $photos = $cafe->photos()->get();
            $photos = $photos->sortBy('sort');
            if(empty($cafe->cover))
                $cafe->cover = $photos->first()->url;  

            $cafe->cafeid=$cafe->id;
            $cafe->id = $index;
            $index++;

            array_push($returnCafes, $cafe);
        }   

        // var_dump($theCafes);

        $markers = $this->getCafeMarkers($returnCafes);

        $nearby = array();
        $nearby["cafes"]=$returnCafes;
        $nearby["markers"]=$markers;

        if(empty($markers))
        {
            $nearby["empty"]="empty";
        }
        else
            $nearby["empty"]="notempty";


        return response()->json($nearby);
    }

    public function Impl_cafesTimeUpdate()
    {
        echo "hi";
        $cafes = Cafe::where('id','>', 1)->get();

        foreach ($cafes as $cafe) {
            # code...
            if($cafe->weekend_close_time)
            {
                $time = $cafe->getWeekendCloseTime;
                $cafe->weekend_close_time1=substr($time->name, 0, 5);
                $cafe->save();
            }
        }
    }

    /**
     * @param 城市编码 citycode  坐标 latlng  区编码 adcode  标签id tag_id  页数(默认值1) page 数量（默认值10）count
     * @return 咖啡馆列表
     */
    public function Impl_cafeslist(Request $request)
    {
        //可能接收到的参数
        $liked=$request->input('liked');
        $visited=$request->input('visited');
        $partner=$request->input('partner');

        $cafe_id=$request->input('cafe_id');
        $lat=$request->input('lat');
        $lng=$request->input('lng');
        $cityCode=$request->input('cityCode');
        $adcode=$request->input('adcode');
        $tagId=$request->input('tag_id');
        $supplyId=$request->input('supply_id');
        $magazine=$request->input('magazine');
        $star=$request->input('star');
        $orderBy=$request->input('orderBy') ?: "id";
        $orderSort=$request->input('orderSort') ?: "asc";
        $dataLength=$request->input('dataLength');

        $loginSession=$request->input('loginSession');
        //标签筛选
        if($tagId)
            $cafes = Tags::find($tagId)->cafes;
        else if($supplyId)
            $cafes = Supplys::find($supplyId)->cafes;
        else
            $cafes = Cafe::where('status', 1)->get();




        $cafes=$cafes->where('status', 1);

        // 表内字段筛选
        if($cityCode)
            $cafes=$cafes->where('citycode', $cityCode);
        if($adcode)
            $cafes=$cafes->where('adcode', $adcode);
        if($magazine)
            $cafes=$cafes->where('magazine', 1);

        if($star)
            $cafes=$cafes->where('star', $star);


        if($partner)
        {
            $partnerCafes=Partner::find($partner)->cafes;

            $partnerCafesArr = array();
            foreach ($partnerCafes as $row) {
                array_push($partnerCafesArr,$row->id);  
            }
            $cafes = $cafes->whereIn('id',$partnerCafesArr);
        }

        if($liked&&$loginSession)      //如果收藏的咖啡馆，返回收藏的咖啡馆
        {
            $cafes=$cafes->where('status', 1);
            $user=$this->getUserByAppUserSession($request->input('loginSession'));    
            $likedCafes=Users::find($user->id)->likeCafes;

            // $likedCafesArr = array();
            // foreach ($likedCafes as $row) {
            //     array_push($likedCafesArr,$row->id);  
            // }

            // $cafes = $cafes->whereIn('id',$likedCafesArr);
            $cafes = $likedCafes;
        }
        if($visited&&$loginSession)      //如果去过的咖啡馆，返回去过的咖啡馆
        {
            $cafes=$cafes->where('status', 1);
            $user=$this->getUserByAppUserSession($request->input('loginSession'));    
            $visitedCafes=Users::find($user->id)->visitedCafes;

            // $visitedCafesArr = array();
            // foreach ($visitedCafes as $row) {
            //     array_push($visitedCafesArr,$row->id);  
            // }
            // $cafes = $cafes->whereIn('id',$visitedCafesArr);
            $cafes = $visitedCafes;
        }
        

        //如果参数中有中心咖啡馆，则以该咖啡馆坐标计算距离
        if($cafe_id)
        {
            $cafe=Cafe::find($cafe_id);
            $arr = explode(',',$cafe->latlng);
            $lng = $arr[0];
            $lat = $arr[1];
        }


        //初步筛选之后，如果有坐标，计算距离，并按照距离排序
        if($lat&&$lng)      //如果参数有位置
        {
            $fiveMilesCafes = collect();
            foreach ($cafes as $cafe) {
                if(!empty($cafe->latlng))
                {
                    $arr = explode(',',$cafe->latlng);
                    $cafelng = $arr[0];
                    $cafelat = $arr[1];
                    $distance = $this->distance($lat,$lng,$cafelat,$cafelng);
                    $cafe->distance=$distance;

                    if($distance<5)
                        $fiveMilesCafes->push($cafe);
                }  
            } 
            $cafes = $fiveMilesCafes;

            $orderBy="distance";
            $orderSort="asc";
        }
        

        


        //数据截取
        if($orderSort=="asc")
            $cafes=$cafes->sortBy($orderBy);
        else
            $cafes=$cafes->sortByDesc($orderBy);

        if($dataLength)
            $cafes=$cafes->take($dataLength);
        else
            $cafes=$cafes->take(10);


        $theCafes = array();        //数据经过sortBy函数后变成了对象，不适合前端处理，重新封装到数组中
        // 整理数据
        foreach ($cafes as $cafe) {
            $tags=$cafe->tags;
            $cafe->cafeTags=$tags->where('category',3);

            if($magazine)
            {
                $supplys = $cafe->supplys;
                $magazineSupplys = array(); 
                foreach ($supplys as $row) {
                    if($row->category=='14')
                    {
                        $row->photos = $row->photos;
                        array_push($magazineSupplys,$row);  
                    }
                }
                $cafe->magazineSupplys = $magazineSupplys;
            }
            
            
            $photos = $cafe->photos()->where('message_id',0)->get();
            $photos = $photos->sortBy('sort');
            if(empty($cafe->cover))
                $cafe->cover = $photos->first()->url;   
            array_push($theCafes,$cafe);
        }   

        return response()->json($theCafes);
    }
    public function Impl_feedsList(Request $request)
    {
        //cafeList,messageList
        $orderBy=$request->input('orderBy') ?: "id";
        $orderSort=$request->input('orderSort') ?: "asc";
        $dataLength=$request->input('dataLength');
        $star=$request->input('star');

        $cafes=Cafe::where('status',1)->get();
        $cafes=$cafes->sortByDesc("id");

        if($star)
            $cafes=$cafes->where('star',$star);

        if($dataLength)
            $cafes=$cafes->take($dataLength);
        else
            $cafes=$cafes->take(10);

        $theCafes = array();        //数据经过sortBy函数后变成了对象，不适合前端处理，重新封装到数组中
        // 整理数据
        foreach ($cafes as $cafe) { 
            $randomPhotos = ($cafe->id)%6+1;
            $photos = $cafe->photos()->where('message_id',0)->get();
            $photos = $photos->take($randomPhotos);

            foreach ($photos as $photo) {
                if(empty($photo->width))
                {
                    $photo->width=1;
                    $photo->height=1;
                }
                $photo->ratio=$photo->width/$photo->height;

                if($photos->count()==6)
                    $photo->ratio=1;
            }

            $cafe->randomPhotos = $randomPhotos;
            $this->layout($photos);
            
            $cafe->photos = $photos;
            array_push($theCafes,$cafe);
        }   

        return response()->json($theCafes);
    }
    public function Impl_swiperList(Request $request)
    {
        $swipers = Swiper::where('status',1)->get();
        return response()->json($swipers);
    }
    public function Impl_feedCafesAndMessages(Request $request)
    {
        //cafeList,messageList
        $orderBy=$request->input('orderBy') ?: "id";
        $orderSort=$request->input('orderSort') ?: "asc";
        $dataLength=$request->input('dataLength');

        $cafes=Cafe::where('status',1)->get();
        $cafes=$cafes->sortByDesc("id");
        if($dataLength)
            $cafes=$cafes->take($dataLength);
        else
            $cafes=$cafes->take(10);

        $theCafes = array();        //数据经过sortBy函数后变成了对象，不适合前端处理，重新封装到数组中
        // 整理数据
        foreach ($cafes as $cafe) { 
            $randomPhotos = ($cafe->id)%6+1;
            $photos = $cafe->photos()->where('message_id',0)->get();
            $photos = $photos->take($randomPhotos);

            foreach ($photos as $photo) {
                if(empty($photo->width))
                {
                    $photo->width=1;
                    $photo->height=1;
                }
                $photo->ratio=$photo->width/$photo->height;

                if($photos->count()==6)
                    $photo->ratio=1;
            }

            $cafe->randomPhotos = $randomPhotos;
            $this->layout($photos);
            
            $cafe->photos = $photos;
            array_push($theCafes,$cafe);
        }   


        $messages=Message::where('status',1)->get();
        $messages=$messages->sortByDesc("id");
        if($dataLength)
            $messages=$messages->take($dataLength);
        else
            $messages=$messages->take(10);

        foreach ($messages as $message) {
            # code...
            $randomPhotos = ($message->id)%6+1;
            $photos = $message->photos()->get();
            $photos = $photos->take($randomPhotos);

            foreach ($photos as $photo) {
                if(empty($photo->width))
                {
                    $photo->width=1;
                    $photo->height=1;
                }
                $photo->ratio=$photo->width/$photo->height;

                if($photos->count()==6)
                    $photo->ratio=1;
            }

            $message->randomPhotos = $randomPhotos;
            $this->layout($photos);
            
            $message->photos = $photos;
            array_push($theCafes,$message);
        }



        return response()->json($theCafes);
    }
    private function layout($photos, $continue = true)
    {
        if($continue)
        {
            if($photos->count()==3||$photos->count()==4)
            {
                $sliceNum = rand(1,3);

                $this->layout($photos->slice(0, $sliceNum), 0);
                $this->layout($photos->slice($sliceNum), 0);
            }
            else if($photos->count()==5)
            {
                $sliceNum = rand(2,3);
                $this->layout($photos->slice(0, $sliceNum), 0);
                $this->layout($photos->slice($sliceNum), 0);
            }
            else if($photos->count()==6)
            {
                $this->layout($photos->slice(0, 3), 0);
                $this->layout($photos->slice(3), 0);
            }
            else
            {
                $rowWidth = 0;
                foreach ($photos as $photo) {
                    $rowWidth += $photo->ratio;
                }

                $i = 0;
                foreach ($photos as $photo) {               //处理细节
                    $photo->rowRatio = $photo->ratio/$rowWidth;
                    $photo->cols = $photos->count();
                    if($photos->count()==1)         //首次分割1个，则一共就一个，长宽比高度
                        $photo->colRatio = 3/$photo->ratio;
                    if($photos->count()==2)
                        $photo->colRatio = 1.7;
                    if($photos->count()==3)
                        $photo->colRatio = 1;

                    $i++;
                    if ( $i == $photos->count() ) {
                        $photo->last = 0;
                    }
                    else
                        $photo->last = 2;
                }
            }
        }
        else
        {
            $rowWidth = 0;
            foreach ($photos as $photo) {
                $rowWidth += $photo->ratio;
            }

            $i = 0;
            foreach ($photos as $photo) {
                //处理细节
                $photo->rowRatio = $photo->ratio/$rowWidth;
                $photo->cols = $photos->count();

                if($photos->count()==1)
                    $photo->colRatio = 1.3;
                if($photos->count()==2)
                    $photo->colRatio = 1.2;
                if($photos->count()==3)
                    $photo->colRatio = 1;

                $i++;
                if ( $i == $photos->count() ) {
                    $photo->last = 0;
                }
                else
                    $photo->last = 2;
            }
        }
        return $photos;
    }

    public function Impl_returnadcode(Request $request){
        $longitude=$request->input('longitude');
        $latitude=$request->input('latitude');
        $latlng=$latitude.",".$longitude;
        $adcode=$this->getAddr($latlng);
        return $adcode->adcode;
    }

    public function getAddr($latlng)
    {
        $homepage = file_get_contents('http://restapi.amap.com/v3/geocode/regeo?output=JSON&location='.$latlng.'&key=291f9ad46a4ab46cc442157ca8b573c8&radius=1000&extensions=all');
        $homepage = json_decode(($homepage));
        $regeocodes = $homepage->regeocode;//逆地理编码列表
        $addressComponent =  $regeocodes->addressComponent;
        return $addressComponent;
    }

    /**
     * @return 返回已上线城市接口
     */
    public function Impl_onlinecity(){
        $citys=City::where('status','1')->get();
        return response()->json($citys);
    }
    public function Impl_getCitys(Request $request){        //
        $status=$request->input('status');
        $appShow=$request->input('appShow');
        $cityCode=$request->input('cityCode');

        $lat=$request->input('lat');
        $lng=$request->input('lng');
        $tagId=$request->input('tag_id');
        $orderBy=$request->input('orderBy') ?: "id";
        $orderSort=$request->input('orderSort') ?: "asc";
        $dataLength=$request->input('dataLength');

        $returnArr = array();         //返回数组
        //是否有当前城市
        if($cityCode>'')
        {
            $citys = City::where('id','>',0)->where('code','<>',$cityCode)->get();
            $city=City::where('code',$cityCode)->first();
            if(!empty($city))
                array_push($returnArr, $city);
        }
        else
        {
            $citys = City::where('id','>',0)->get();
        }
        
        if($appShow)
            $citys=$citys->where('appShow', $appShow);
        if($status)
            $citys=$citys->where('status', $status);

        if($dataLength)
            $citys=$citys->take($dataLength);
        else
            $citys=$citys->take(10);


        // 整理数据
        foreach ($citys as $city) {
            array_push($returnArr, $city);
        } 
        

        return response()->json($returnArr);

    }
    public function Impl_getMessages(Request $request){        //
        $cafe_id=$request->input('cafe');
        $orderBy=$request->input('orderBy') ?: "id";
        $orderSort=$request->input('orderSort') ?: "asc";
        $dataLength=$request->input('dataLength');

        $returnArr = array();         //返回数组
        //是否有当前城市
        $messages = Message::where('cafe_id','=',$cafe_id)->get();

        if($orderSort=="asc")
            $messages=$messages->sortBy($orderBy);
        else
            $messages=$messages->sortByDesc($orderBy);

        if($dataLength)
            $messages=$messages->take($dataLength);
        else
            $messages=$messages->take(10);


        // 整理数据
        foreach ($messages as $message) {
            $user = Users::find($message->user_id);
            // $user->forget('password');

            $message->user=$user;
            $message->photos=$message->photos;
            array_push($returnArr, $message);
        } 
        
        return response()->json($returnArr);

    }

    public function Impl_getMessagesAll(Request $request){        //


        $user=$this->getUserByAppUserSession($request->input('loginSession'));
        $orderBy=$request->input('orderBy') ?: "id";
        $orderSort=$request->input('orderSort') ?: "asc";
        $dataLength=$request->input('dataLength');



        $returnArr = array();         //返回数组


        // $saleOrders = Sale_order::where('user_id','=',$user->id)->where('status','=',1)->get();
        $messages = Message::where('user_id','=',$user->id)->get();

        // if($orderSort=="asc")
        //     $messages=$messages->sortBy($orderBy);
        // else
        $messages=$messages->sortByDesc($orderBy);

        if($dataLength)
            $messages=$messages->take($dataLength);
        else
            $messages=$messages->take(10);

        

        // 整理数据
        foreach ($messages as $message) {
            $message->user=$user;
            $message->cafe=$message->getCafe;
            $message->photos=$message->photos;
            array_push($returnArr, $message);
        } 
        
        return response()->json($returnArr);

    }

    /**
     * @return 返回咖啡馆标签,按照后台顺序
     */
    public function Impl_cafetags(){
        $tags=Tags::where('category','3')
        ->orderBy('sort','asc')
        ->get();
        return response()->json($tags);
    }

    /**
     * @param gps或者citycode或者id
     * @return  返回城市详情
     */

    public function Impl_detailcity(Request $request){

        $citycode=$request->input('citycode');
        if($citycode){
            $city=City::where('code',$citycode)->where('status',1)->first();
            if(!$city){
                return response()->json("-1");
            }
        }
        $cafes = $city->cafes->sortByDesc('id');
        $districts=$cafes->groupBy('adcode');
        $districtArr=array();
        $i=0;
        foreach ($districts as $district){
            $districtArr[$i]['district']= $district[0]->district;
            $districtArr[$i]['adcode']= $district[0]->adcode;
            $i++;
        }
        $city->districts=$districtArr;

        return response()->json($city);
    }
    public function Impl_infoCity(Request $request){

        $id=$request->input('id');
        $citycode=$request->input('citycode');

        if($citycode){
            $city=City::where('code',$citycode)->first();
        }
        
        if($id){
            $city=City::find($id);
        }

        return response()->json($city);
    }
    public function cityTags(Request $request){


//        $id=$request->id;
//        $num=$request->num ?: 7;
//        $city=Citys::find($id);
//        $cafes=$city->cafes;
//        $tagArr=array();
//        foreach ($cafes as $cafe){
//            foreach ($cafe->tags->where('category',3) as $tag){
//                array_push($tagArr,$tag);
//            }
//        }
//        $collect=collect($tagArr)->groupBy('id');
//        $sort=array();
//        foreach ($collect as $item){
//            $sort[$item->count()]=$item;
//        }
//        rsort($sort);
//
//        $sort=array_slice($sort,0,$num);
//        $i=0;
//        foreach ($sort as $item) {
//            $sort[$i] = $item[0];
//            $sort[$i]->cafes = Tags::find($item[0]->id)->cafes->where('citycode', $city->code)->where('status',1);
//            foreach ($sort[$i]->cafes as $cafe) {
//                $tags = $cafe->tags;
//                $cafe->cafeTags = $tags->where('category', 3);
//                $photos = $cafe->photos()->where('message_id', 0)->get();
//                $photos = $photos->sortBy('sort');
//                if (empty($cafe->cover))
//                    $cafe->cover = $photos->first()->url;
//            }
//            $i++;
//        }
        $code=$request->code;
        $tags=Tags::where('public',1)->where('category',3)->get();
        foreach ($tags as $tag){
            $cafes=$tag->cafes()->where('citycode',$code)->where('star','>','3');
            $tag->count=$cafes->count();
            if($tag->count>4){
                $tag->cafes=$cafes->get();
                foreach ($tag->cafes as $cafe){
                    $photos = $cafe->photos()->where('message_id', 0)->get();
                    $photos = $photos->sortBy('sort');
                    if (empty($cafe->cover))
                        $cafe->cover = $photos->first()->url;
                }
            }else{
                $tag->cafes="";
            }
        }
        $tagArr=array();
        $sorted = $tags->sortByDesc('count')->take(8);
        foreach ($sorted as $item) {
            array_push($tagArr,$item);
        }
        return response()->json($tagArr);
     //  return response()->json($sort);

    }

    public function cityRecommend(Request $request){
        $dataLength=$request->input('dataLength');
        $cityCode=$request->cityCode ;

        $cafes=Cafe::where('status', 1)->where('citycode',$cityCode)->orderBy('star', 'desc')->get();
        if($dataLength)
            $cafes=$cafes->take($dataLength);
        else
            $cafes=$cafes->take(10);

        $theCafes = array();        //数据经过sortBy函数后变成了对象，不适合前端处理，重新封装到数组中
        // 整理数据
        foreach ($cafes as $cafe) {
            $tags=$cafe->tags;
            $cafe->cafeTags=$tags->where('category',3);

            $photos = $cafe->photos()->where('message_id',0)->get();
            $photos = $photos->sortBy('sort');
            if(empty($cafe->cover))
                $cafe->cover = $photos->first()->url;
            array_push($theCafes,$cafe);
        }

        return response()->json($theCafes);

    }
    public  function  citySift(Request $request){
        //dd(Cafes::find(1030)->photos()->get());
        $dataLength=$request->input('dataLength') ;
        $adcode=$request->adcode ?: "";
        $citycode=$request->citycode ?: "";
        $tagId=$request->tagId ?: "";
        $tagIdArr = explode(',',$tagId);
        array_shift($tagIdArr);
        if($adcode==""){
            $cafes=Cafe::where('citycode',$citycode);
        }else{
            $cafes=Cafe::where('adcode',$adcode);
        }
        if($tagId!=""){
            $cafes=$cafes->join('cafe_tag',function ($join) use ($tagIdArr){
                $join->on('cafes.id', '=', 'cafe_tag.cafe_id')->whereIn('tag_id',$tagIdArr);
            })->select('cafes.*');
        }
        $cafes=$cafes->where('status',1)->get();
        $cafes=$cafes->unique('id');
        if($dataLength)
            $cafes=$cafes->take($dataLength);
        else
            $cafes=$cafes->take(20);

        $theCafes = array();        //数据经过sortBy函数后变成了对象，不适合前端处理，重新封装到数组中
        // 整理数据
        foreach ($cafes as $cafe) {
         
            $tags=$cafe->tags;
            $cafe->cafeTags=$tags->where('category',3);
            $photos = $cafe->photos()->where('message_id',0)->get();
            $photos = $photos->sortBy('sort');
            if(empty($cafe->cover)){
                $cafe->cover = $photos->first()->url;
            }
            array_push($theCafes,$cafe);
        }
        return response()->json($theCafes);

    }
    public function cityTags2 (){
        $tags=Tags::where('public',1)->where('category',3)->get();
        foreach ($tags as $tag){
            $cafes=$tag->cafes()->where('citycode','0535')->where('star','>','3');
            $tag->count=$cafes->count();
            $tag->cafes=$cafes->get();
            foreach ($tag->cafes as $cafe){
                $photos = $cafe->photos()->where('message_id', 0)->get();
                $photos = $photos->sortBy('sort');
                if (empty($cafe->cover))
                    $cafe->cover = $photos->first()->url;
            }
        }
        $sorted = $tags->sortByDesc('count')->take(8);
        return response()->json($sorted);

    }
    public function Impl_detailPartner(Request $request){

        $id=$request->input('id');
        $partner=Partner::find($id);
        $cafes = $partner->cafes;
        $allCafes= array();
        $onlineCafes = array();

        foreach ($cafes as $key) {
            array_push($allCafes, $key);
            if($key->status == 1)
                array_push($onlineCafes, $key);
        }
        $partner->allCafes = $allCafes;
        $partner->onlineCafesCount = count($onlineCafes);
        $partner->menus = $partner->menus;
        
        return response()->json($partner);
    }
    public function Impl_detailMessage(Request $request){

        $id=$request->input('id');
        $message=Message::find($id);

        $photos=$message->photos;
        $photosArr = array();
        foreach ($photos as $photo) {
            array_push($photosArr, $photo->url);
        }
        $message->photosArr=$photosArr;        
        return response()->json($message);
    }
    public function Impl_getPartners(Request $request)
    {
        $partners=Partner::where('status',1)->orderBy('sort', 'asc')->get();
        $role_id=$request->input('role_id');
        if($role_id)
            $partners = Partner::where('role_id',$role_id)->get();
        return response()->json($partners);
    }
    /**
     * @param 区编码adcode
     * @return 区的详细信息
     */
    public function  Impl_detaildistrict(Request $request){
        $adcode=$request->input('adcode');
        $district=District::where('adcode',$adcode)->get();

        $district = $district[0];

        $cafes = $district->getCafes;
        $cafes=$cafes->where('status', 1);
        $markers = $this->getCafeMarkers($cafes);

        $district->cafes = $cafes;
        $district->markers = $markers;

        $city=$district->getCity;
        if(empty($district->lat))       //如果没有区的坐标，更新到数据库
        {
            $gps = $this->getGps($city->name.$district->name);
            $arr = explode(',',$gps);
            $district->lng = $arr[0];
            $district->lat = $arr[1];
            $dis = District::find($district->id);
            $dis->lng = $arr[0];
            $dis->lat = $arr[1];
            $dis->save();
        }

        return response()->json($district);
    }

    public function userList(Request $request){
        $role=$request->input('role');
        $orderSort=$request->input('orderSort') ?: "asc";
        $dataLength=$request->input('dataLength');
        
        $users=Users::where('role',$role)->get();
        


        
        $users=$users->sortByDesc("id");


        if($dataLength)
            $users=$users->take($dataLength);
        else
            $users=$users->take(10);

        return response()->json($users);
    }

    /**
     * @param code
     * @return 登录open_id,登录密钥session_key
     */
    public function  onLogin(Request $request){
        $code=$request->input('code');

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".config('app.mini_programe.appid')."&secret=".config('app.mini_programe.secret')."&js_code=".$code."&grant_type=authorization_code";

        $res = json_decode($this->httpGet($url));
        // echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@";
        // var_dump($res);
        $userSession = str_random(128);
        Redis::set($userSession,$res->openid);  
        return response()->json($userSession);
    }
    // 暖百家登录
    public function  onNuan100Login(Request $request){
        $code=$request->input('code');

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx4005b6580d9b88a3&secret=8418deb8f2f67cba2296ad73435c6757&js_code=".$code."&grant_type=authorization_code";

        $res = json_decode($this->httpGet($url));
        // echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@";
        // var_dump($res);
        $userSession = str_random(128);
        Redis::set($userSession,$res->openid);  
        return response()->json($userSession);
    }
    // 啡鳥集登录
    public function  onFeiNiaoLogin(Request $request){
        $code=$request->input('code');

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx9911ad4e2a4fd275&secret=3a5ff762865187ffa0f8a6ff9683fa84&js_code=".$code."&grant_type=authorization_code";

        $res = json_decode($this->httpGet($url));
        // echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@";
        // var_dump($res);
        $userSession = str_random(128);
        Redis::set($userSession,$res->openid);
        return response()->json($userSession);
    }
    public function Impl_setUserLikeCafe(Request $request){
        $user=$this->getUserByAppUserSession($request->input('loginSession'));
        return $this->setUserLikeCafe($user->id,$request->input('cafe_id'),$request->input('isLike'));
    }
    public function Impl_setUserVisitCafe(Request $request){
        $user=$this->getUserByAppUserSession($request->input('loginSession'));
        return $this->setUserVisitCafe($user->id,$request->input('cafe_id'),$request->input('isVisited'));
    }


    private function getUserByAppUserSession($loginSession){
        $wx_app_openid=Redis::get($loginSession);
        $user = DB::table('users')->select("id")->where('wx_app_openid', $wx_app_openid)->first();
        return $user;
    }


    //设置用户收藏或者取消收藏咖啡馆，参数用户id，咖啡馆id，当前like状态；返回"0"or"1""
    private function setUserLikeCafe($user_id,$cafe_id,$isLike)
    {
        //如果已收藏，取消收藏
        if($isLike)
        {
            User_likeCafe::where('cafe_id',$cafe_id)
            ->where('user_id',$user_id)
            ->delete();
            return 0;
        }
        else
        {
            $ulc=new User_likeCafe();
            $ulc->user_id = $user_id;
            $ulc->cafe_id = $cafe_id;
            
            $ulc->save();
            return 1;

        }
        
    }
    private function setUserVisitCafe($user_id,$cafe_id,$isVisited)
    {
        //如果已收藏，取消收藏
        if($isVisited)
        {
            UserVisitedCafe::where('cafe_id',$cafe_id)
            ->where('user_id',$user_id)
            ->delete();
            return 0;
        }
        else
        {
            $ulc=new UserVisitedCafe();
            $ulc->user_id = $user_id;
            $ulc->cafe_id = $cafe_id;
            $ulc->save();
            return 1;
        }
        
    }

    //用户是否收藏咖啡馆，返回1或者0
    private function getUserLikeCafe($user_id,$cafe_id)
    {
        $count = User_likeCafe::where('user_id',$user_id)
        ->where('cafe_id',$cafe_id)
        ->count();
        if($count)
            return 1;
        else
            return 0;
    }
    private function getUserVisitCafe($user_id,$cafe_id)
    {
        $count = UserVisitedCafe::where('user_id',$user_id)
        ->where('cafe_id',$cafe_id)
        ->count();
        if($count)
            return 1;
        else
            return 0;
    }


    //根据3rd_session得到客户端登录用户
    // private function getUserByAppUserSession($userSession)
    // {
    //     //如果查询到该用户，更新并返回; 否则保存并返回


    // }
    /*
     * 一些可以拿出来的功能放在这里
     * 咖啡馆地图marker
     */

    private function getBean($bean)
    {
        if(!empty($bean->dict_id))
            $bean->continent = $bean->continent;
        if(!empty($bean->tag_id))
            $bean->country = $bean->country;
        return $bean;
    }

    private function getCafeMarkers($cafes)
    {
        $markers = array();
        $index = 0;
        foreach ($cafes as $cafe) {
            if(!empty($cafe->latlng))
            {
                $latlng = explode(',', $cafe->latlng);

                $marker["id"] = $cafe->id;
                $marker["cafeid"] = $cafe->cafeid;
                $marker["name"] = $cafe->name;
                $marker["latitude"]=(float)$latlng[1];
                $marker["longitude"]=(float)$latlng[0];
                $marker["width"]=15;
                $marker["height"]=30;

                array_push($markers, $marker);
                // $markers[$cafe->id] = $marker;
                $index++;
            } 
        }
        return $markers;
    }
    /*
     * 附近咖啡馆计算公式
     */
    private function distance($lat1, $lng1, $lat2, $lng2, $miles = true)
    {
        $pi80 = M_PI / 180;
        $lat1 *= $pi80;
        $lng1 *= $pi80;
        $lat2 *= $pi80;
        $lng2 *= $pi80;
        $r = 6372.797; // mean radius of Earth in km
        $dlat = $lat2 - $lat1;
        $dlng = $lng2 - $lng1;
        $a = sin($dlat/2)*sin($dlat/2)+cos($lat1)*cos($lat2)*sin($dlng/2)*sin($dlng/2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        $km = $r * $c;
        $dis = ($miles ? ($km * 0.621371192) : $km);
        return round($dis,1);
    }
    //地理编码
    private function getGps($address)
    {
        $homepage = file_get_contents('http://restapi.amap.com/v3/geocode/geo?address='.$address.'&output=JSON&key=291f9ad46a4ab46cc442157ca8b573c8');
        $homepage = json_decode(($homepage));
        $formatted_address = $homepage->geocodes;         //地理编码列表
        $location =  $formatted_address[0]->location;
        return $location;
    }

    public function Impl_getCityCode(Request $request)
    {
        $lat=$request->input('lat');
        $lng=$request->input('lng');

        //根据坐标拿到城市，先筛选一遍
        $latlng = $lng.",".$lat;
        $cityCode=$this->getCitycodeByGps($latlng);
        return response()->json($cityCode);
    }

    private function getCitycodeByGps($latlng)
    {
        $homepage = file_get_contents('http://restapi.amap.com/v3/geocode/regeo?output=JSON&location='.$latlng.'&key=291f9ad46a4ab46cc442157ca8b573c8&radius=1000&extensions=all');
        $homepage = json_decode(($homepage));
        $regeocodes = $homepage->regeocode;//逆地理编码列表
        $addressComponent =  $regeocodes->addressComponent;
        return $addressComponent->citycode;
    }
    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
    public function Impl_searchCitys(Request $request){
        $keyWords=$request->keyWords;
        $loginSession=$request->loginSession;
        $user=$this->getUserByAppUserSession($loginSession);
        $citys=City::where('name','like','%'.$keyWords.'%');
        if($keyWords==""){
            $citys=$citys->where('status',1);
        }
        $cityArr=array();
        foreach ($citys->get() as $city){
            array_push($cityArr,$city);
        }
        if($citys->count()==0){
            $cityArr[0]['info']="输入有误";
        }else{
            $cityArr[0]['info']="1";

        }
        return response()->json($cityArr);
    }

}
